import datetime
import re
import time

from django_redis import get_redis_connection
from rest_framework import serializers
from rest_framework_jwt.settings import api_settings

from complains.models import Complain
from news.models import News
from quesanw.models import QuestionModel, AnswerModel, QuestionFocusModel, UserFocusTagModel, TagModel, QuestionTagModel
from users import constants
from users.models import User, UserInfo


#
# class ImageCodeCheckSerializer(serializers.Serializer):
#     """图形验证码序列化器"""
#     image_code_id = serializers.UUIDField()
#     text = serializers.CharField(max_length=4,min_length=4)
#     def validate(self, attrs):
#         """检验"""
#         # 获取参数
#         image_code_id = attrs['image_code_id']
#         text = attrs['text']
#
#         redis_conn = get_redis_connection('verify_codes')
#         image_code_text = redis_conn.get('img%s'% image_code_id)
#         # print(image_code_text)
#
#         if not image_code_text:
#             return serializers.ValidationError('图形验证码无效')
#         # 删除验证码　防止恶意多次尝试
#         redis_conn.delete('img%s'% image_code_id)
#
#         # 比较图形验证码
#         image_code_text =image_code_text.decode('gbk')
#         print(image_code_text)
#         if image_code_text.lower() != text.lower():
#             raise serializers.ValidationError("图片验证码错误")
#
#         # 验证短信验证是否在６０秒内内
#         mobile = self.context['view'].kwargs['mobile']
#         send_flag = redis_conn.get('send_flag_%s'% mobile)
#         if send_flag:
#             raise serializers.ValidationError('请求过于频繁')
#
#         return attrs



class CreateUserSerializer(serializers.ModelSerializer):
    """
           用户注册
           传入参数：
               username, password, password2, sms_code, mobile, allow
           """

    sms_code = serializers.CharField(label='短信验证码', max_length=6, min_length=6, write_only=True)
    allow = serializers.CharField(label='同意协议', write_only=True)

    class Meta:
        model = User
        fields = ('id', 'username', 'password', 'sms_code', 'mobile', 'allow')

        extra_kwargs = {
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }

        }

    def validate_mobile(self, value):
        """校验手机号"""
        if not re.match(r'1[3-9]\d{9}', value):
            raise serializers.ValidationError("手机号错误")
        return value

    def validate_allow(self, value):
        """校验协议"""
        if not value == 'true':
            raise serializers.ValidationError('请同意协议后注册')
        return value

    def validate(self, data):
        """检验两次密码"""

        reids_conn = get_redis_connection('verify_codes')
        mobile = data['mobile']
        sms_code = reids_conn.get('sms_%s' % mobile)
        if not sms_code:
            raise serializers.ValidationError("无效的短信验证码")
        if data['sms_code'] != sms_code.decode():
            raise serializers.ValidationError('短信验证码错误')

        return data

    def create(self, valideted_data):
        print('创建用户')
        """
                创建用户
                """
        # 删除valideted_data中不需要存入的字段

        del valideted_data['sms_code']
        del valideted_data['allow']
        # 继承父类中的新建用户的方法
        user = super().create(valideted_data)
        # 把密码加密保存
        user.set_password(valideted_data['password'])

        user.save()

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token

        return user


class UserSerializer(serializers.ModelSerializer):
    """用户序列化器"""

    class Meta:
        model = User
        fields = ('username', 'id')


class UserDetailSerializer(serializers.ModelSerializer):
    """用户信息序列化器"""

    class Meta:
        model = UserInfo
        fields = ['address', 'school', 'company', "persurl", 'persintro', 'city', 'nick_name']





class TagSerialiaer(serializers.ModelSerializer):
    """标签详情序列化器"""

    class Meta:
        model = TagModel
        fields = '__all__'


class QuestionSerializer(serializers.ModelSerializer):
    """问题序列化器"""

    # id = QuestionTagModelSerializer(many=True)
    class Meta:
        model = QuestionModel
        fields = ('title', 'count', "update_time", 'id', 'author')


class QuestionTagModelSerializer(serializers.ModelSerializer):
    """问题所属标签序列化器"""
    # tag = TagSerialiaer(many=True)
    # question = QuestionSerializer

    class Meta:
        model = QuestionTagModel
        fields = '__all__'



class MyQuestionSerializer(serializers.ModelSerializer):
    """我的提问接口"""

    # id = QuestionTagModelSerializer(many=True)
    author = UserSerializer()

    class Meta:
        model = QuestionModel
        fields = ('title', 'count', "update_time", 'id', 'author','tags')

class MyAnwserSerializer(serializers.ModelSerializer):
    """我的回答接口"""
    question = MyQuestionSerializer()

    class Meta:
        model = AnswerModel
        fields = ('count', "update_time", 'id', 'question', 'detail')


class MyfocusQuestion(serializers.ModelSerializer):
    """我关注的问题序列化器"""

    # question = QuestionSerializer()
    class Meta:
        model = QuestionFocusModel
        fields = '__all__'
        depth = 2






class MyfocusTag(serializers.ModelSerializer):
    """我关注的标签"""
    tag = TagSerialiaer()

    class Meta:
        model = UserFocusTagModel
        fields = '__all__'


class AddUserBrowsingHistorySerializer(serializers.Serializer):
    """
    添加用户浏览历史序列化器
    """
    history_type = serializers.CharField(label='浏览的模块',max_length=20)
    history_id = serializers.IntegerField(label="商品SKU编号", min_value=1)

    def validate(self, attrs):

        history_type = attrs.get('history_type')

        history_id = attrs.get("history_id")

        # if history_id and history_type:
        if history_type == "head":
            try:
                News.objects.get(id=history_id)
            except News.DoesNotExist:
                raise serializers.ValidationError('没有这条新闻')

        elif history_type == 'question':
            try:
                QuestionModel.objects.get(id=history_id)
            except QuestionModel.DoesNotExist:
                raise serializers.ValidationError('没有这个问题')
        elif history_type=='spit':
            try:
                Complain.objects.get(id=history_id)
            except Complain.DoesNotExist:
                raise serializers.ValidationError('没有这个吐槽')
        return attrs

    def create(self, validated_data):
        """保存浏览历史记录"""

        username = self.context['request'].user.username
        history_tpye = validated_data['history_type']
        history_id =validated_data['history_id']
        time_ = int(time.mktime(datetime.datetime.now().timetuple()))

        # 保存到redis里面
        if history_tpye == "news":
            redis_conn = get_redis_connection('history')
            pl = redis_conn.pipeline()

            # # 移除已经存在的本商品浏览记录
            # pl.zrem("history_news_%s"%username , history_id)  自动去重
            # 添加新的浏览记录
            pl.zadd("history_news_%s"%username,time_,history_id )
            # 只保存最多5条记录
            pl.zrange("history_news_%s"%username,start=0,end=constants.USER_BROWSING_HISTORY_COUNTS_LIMIT ,desc=False,)
            pl.execute()
            return validated_data

        elif history_tpye == 'question':
            redis_conn = get_redis_connection('history')
            pl = redis_conn.pipeline()


            # 添加新的浏览记录
            pl.zadd("history_question_%s" % username,time_, history_id)
            # 只保存最多5条记录
            pl.zrange("history_question_%s" % username, start=0,end=constants.USER_BROWSING_HISTORY_COUNTS_LIMIT ,desc=False,)

            pl.execute()

            return validated_data


        elif history_tpye=='spit':
            redis_conn = get_redis_connection('history')
            pl = redis_conn.pipeline()


            # 添加新的浏览记录
            pl.zadd("history_spit_%s" % username,time_, history_id)
            # 只保存最多5条记录
            pl.zrange("history_spit_%s" % username, start=0,end=constants.USER_BROWSING_HISTORY_COUNTS_LIMIT ,desc=False,)
            pl.execute()

            return validated_data


class NewsSerializer(serializers.ModelSerializer):
    """x新闻浏览历史记录"""
    class Meta:
        model = News
        fields =('title',)
class QuestionTitleSerializer(serializers.ModelSerializer):
    """问题浏览历史记录"""
    class Meta:
        model = QuestionModel
        fields =('title',)

class TagTitleSerializer(serializers.ModelSerializer):
    """吐槽记录序列化器"""
    class Meta:
        model = Complain
        fields =('content',)


class SetCityserializer(serializers.ModelSerializer):

    class Meta:
        model=UserInfo
        fields="__all__"

    # def update(self, instance, validated_data):
    #     print('city',validated_data)
    #     instance.city = validated_data.get("city")
    #     print(validated_data['city'])
    #     instance.save()
    #     return instance
class PersonalCountSerializer(serializers.ModelSerializer):

    class Meta:
        model=UserInfo
        fields="__all__"
        depth=1


class PersonalCountChangeSerializer(serializers.ModelSerializer):

    class Meta:
        model=User
        fields='__all__'


class FocusQestionSerilizer(serializers.ModelSerializer):
    class Meta:
        model = QuestionFocusModel
        fields = '__all__'

    def create(self, validated_data):
        user = self.context["view"].user.id
        question = validated_data['question']
        focusquestion = QuestionFocusModel.ojects.filter(user=user,question=question )
        if focusquestion:
            raise serializers.ValidationError('已关注')
        super().create(validated_data)
        return validated_data